class WeekTimeSheetsController < ApplicationController
  before_filter :require_any_user
  skip_before_filter :verify_authenticity_token, :only=>[:up,:show_all]

  def index
    @tasks=Task.find :all, :conditions=>"user_id="+current_user.id.to_s+" and project_id!=1"
    arr=[  ]
    @tasks.each{ |task|

      curr_task_start_date = task.start_date.to_date.monday
      task_end_date = (task.end_date.to_date).monday

      while(curr_task_start_date <= task_end_date)

         status='<font color=brown>Nuevo</font>'
         thisWTS=task.week_time_sheets.find :all, :conditions=>"start_date='"+curr_task_start_date .to_s+"'"

            if ( thisWTS.size>0)
                status='<font color=orange>En Edición</font>'
            end

            if  thisWTS.size>0 && thisWTS[0].submit==1 && thisWTS[0].active==0
                  status='<font color=red>Enviado</font>'
            end
         
            if  thisWTS.size>0 && thisWTS[0].active==1
                    status='<font color=green>Aceptado</font>'
            end
            arr << [curr_task_start_date ,  status]
            curr_task_start_date += 7
      end

    }
    @dates=arr.uniq
    
  end

  def submit
    ids=params['id'].split(",")
    ids.each{ |i|
      i=i.to_i
      if i > 0
        thisWTS=WeekTimeSheet.find(i)
        thisWTS.submit='1'
        thisWTS.save
      end
    }
  end


  def edit

    @monday=params[:myDate].to_date.monday
    respond_to do |format|
      format.html
      format.xml  { render :xml => @week_time_sheet }
    end
    
  end


  def up
    #It never gonna be a negative number
    #como característica cuando la tarea tenga el 100% de completado no se mostrará 
    a={:monday_time=>params['c3'],:tuesday_time=>params['c4'],:wednessday_time=> params['c5'],:thursday_time=> params['c6'],:friday_time=> params['c7'],:saturday_time=> params['c8'],:sunday_time=> params['c9']}
    @wts = WeekTimeSheet.find(params[:gr_id])
    
    if @wts.task.percentage!=params['c1'].to_i
      @wts.task.percentage=params['c1'].to_i
        if @wts.task.percentage==0
          @wts.task.status="Nuevo"
        else
          if (@wts.task.percentage>0 && @wts.task.percentage<100)
            @wts.task.status="En proceso"
          else
            @wts.task.status="Completado"
          end
        end
    else
        @wts.task.status=params['c2']
    end
    
    @wts.task.save
    @wts.update_attributes( a )
    
  end


  def show_all

    #---------- Dates and configuration
    response.headers["Content-Type"] = 'text/xml'
    now=Date.today.to_s
    @monday=Date.today.monday
    if params['start_date'].nil?
      sd=@monday
    else
      sd=(params['start_date']).to_date
    end
    @sd=sd
    ####################### firstable ##################
    # I check the general overhead hrs for current_user
          v=Task.find :all, :conditions=>"name='Vacaciones' and user_id='"+current_user.id.to_s+"' and project_id=1", :limit=>"1"
          if (v.size==0)
            t=Task.create(:name=>'Vacaciones',:descripcion=>'Horas tomadas para vacaciones',:start_date=>'1969-01-01',:end_date=>'2060-01-01',:current_start_date=>'1969-01-01',:current_end_date=>'2060-01-01',:percentage=>0,:status=>' ',:project_id=>1,:user_id=>current_user.id)
            t.save
          end

          e=Task.find :all, :conditions=>"name='Enfermedad' and user_id='"+current_user.id.to_s+"' and project_id=1", :limit=>"1"
          if (e.size==0)
            t=Task.create(:name=>'Enfermedad',:descripcion=>'Horas tomadas debido a enfermedad',:start_date=>'1969-01-01',:end_date=>'2060-01-01',:current_start_date=>'1969-01-01',:current_end_date=>'2060-01-01',:percentage=>0,:status=>' ',:project_id=>1,:user_id=>current_user.id)
            t.save
          end

          g=Task.find :all, :conditions=>"name='Generales' and user_id='"+current_user.id.to_s+"' and project_id=1", :limit=>"1"
          if (g.size==0)
            t=Task.create(:name=>'Generales',:descripcion=>'Horas tomadas debido a enfermedad',:start_date=>'1969-01-01',:end_date=>'2060-01-01',:current_start_date=>'1969-01-01',:current_end_date=>'2060-01-01',:percentage=>0,:status=>' ',:project_id=>1,:user_id=>current_user.id)
            t.save
          end



    #project must be started and At teast one task must be available for this user (please see view for this last condition)
    @projectsFromDB=Project.find :all, :conditions=>( "startDate <= '"+(sd+6).to_s+"'")
    @projs4ThisWeek=[]
    @projectsFromDB.each{ |project|
      id_p=project.id
      #----------- Request for every TimeSheet within Task for the selected week ( params[:start_date] )
      tasksFromCondition=project.tasks.find :all, :conditions=> ("user_id='"+current_user.id.to_s+"'")
      p=project.clone
      p.tasks=[]
      tasksFromCondition.each do |thisTask|
        #if thisTask.start_date.to_date.monday <= sd+6 && thisTask.percentage<100
        if thisTask.percentage<100
          p.tasks<<thisTask
        end
      end
      @projs4ThisWeek << p
    }
    #we've got all Tasks currently started, now, here we go until reach the WTS
    
    @projs4ThisWeek.each do |p|
      p.tasks.each do |t|

        #----------- Ordering everything for XML response
       thisWTS=WeekTimeSheet.find(:all, :conditions => 'task_id='+t.id.to_s+" and start_date='"+sd.to_s+"'"+" and submit=0", :limit=>"1")
       if thisWTS.size == 0 #La hoja semanal fue mandada? si lo fue ya no la muestres, si no ha sido creada creala
            sent=WeekTimeSheet.find(:all, :conditions => 'task_id='+t.id.to_s+" and start_date='"+sd.to_s+"'"+" and submit=1", :limit=>"1")
              if sent[0].nil?
                w=WeekTimeSheet.new( :task_id=>t.id , :created_at=>now.to_s , :updated_at=>now.to_s , :submit=>'0' , :start_date=>sd.to_s, :submit=>0,:active=>0)
                w.save
              end
       else
          w= WeekTimeSheet.find(thisWTS[0].id)    
       end

      end
    end
    
  end

  def start_date
    if params['id'].nil?
      sd=@monday=Date.today.monday
    else
      sd=(params['id']).to_date
    end
    @myDate=sd;
    @outHeader="Nombre,%,Estado,Lu("+(sd).to_s(:short)+"),Ma("+(sd+1).to_s(:short)+"),Mi("+(sd+2).to_s(:short)+"),Ju("+(sd+3).to_s(:short)+"),Vi("+(sd+4).to_s(:short)+"),Sa("+(sd+5).to_s(:short)+")"+",Do("+(sd+6).to_s(:short)+"),Suma";
  end

  def status

    @monday=Date.today.monday
    if params['start_date'].nil?
      sd=@monday
    else
      sd=(params['start_date']).to_date
    end
    @sd=sd


    #project must be started and At teast one task must be available for this user (please see view for this last condition)
    @projectsFromDB=Project.find :all, :conditions=>( "startDate <= '"+(sd+6).to_s+"'")
    @projs4ThisWeek=[]
    @projectsFromDB.each{ |project|
      id_p=project.id
      #----------- Request for every TimeSheet within Task for the selected week ( params[:start_date] )
      tasksFromCondition=project.tasks.find :all, :conditions=> ("user_id='"+String(current_user.id)+"'")
      p=project.clone
      p.tasks=[]
      tasksFromCondition.each do |thisTask|
        if thisTask.start_date.to_date.monday <= sd+6 && thisTask.percentage<100
          p.tasks<<thisTask
        end
      end
      @projs4ThisWeek << p
    }
    #we've got all Tasks currently started, now, here we go until reach the WTS

    @status="Nuevo"
    @projs4ThisWeek.each do |p|
      p.tasks.each do |t|

        #----------- Ordering everything for XML response
       thisWTS=WeekTimeSheet.find(:all, :conditions => 'task_id='+t.id.to_s+" and start_date='"+sd.to_s+"'", :limit=>"1")
       if thisWTS.size > 0
          w= WeekTimeSheet.find(thisWTS[0].id)
          #TODO: When the user add a taks from this project and the user view their old time sheet it's gonna crash!
          if w.submit==0 && @status=="Nuevo"
            @status="En Edición"
          end
          if  w.submit==1 && w.active==0 && (@status=="Nuevo" || @status=="En Edición")
            @status="Enviado"
          end
          if  w.active==1 && w.active==1 && (@status=="Nuevo" || @status=="En Edición")
            @status="Aceptado"
          end
      end

      end
    end    
    
  end


end
